﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Gurucore.Framework.Core.Proxy;
using Gurucore.Framework.DataAccess;

namespace Gurucore.Framework.Business.TransactionContext
{
	public class BeforeInterceptor : InterceptorBase
	{
		public override object Intercept(object p_oInstance, System.Reflection.MethodInfo p_oMethod, InterceptorType p_eInterceptorType, params object[] p_arrArg)
		{
			DataAccessContext oDACtx = DataAccessContext.GetDataAccessContext();

			object[] arrAttr = p_oInstance.GetType().BaseType.Assembly.GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
			string sAssemblyID = string.Empty;
			if (arrAttr.Length == 1)
			{
				sAssemblyID = ((System.Runtime.InteropServices.GuidAttribute)arrAttr[0]).Value;
			}

			object[] arrTransAttr = p_oMethod.GetCustomAttributes(typeof(TransactionBoundAttribute), true);
			if (arrTransAttr.Length > 0)
			{
				//Console.WriteLine("Begin Transaction");
				oDACtx.EnterTransaction();
			}

			object[] arrDSAttr = p_oMethod.GetCustomAttributes(typeof(DataSourceAttribute), true);
			if (arrDSAttr.Length > 0)
			{
				DataSourceAttribute oDSAttr = (DataSourceAttribute)arrDSAttr[0];
				oDACtx.SetCurrentDataSource(sAssemblyID, oDSAttr.Name);
			}
			else
			{
				//default datasource
				oDACtx.SetCurrentDataSource(sAssemblyID, string.Empty);
			}

			return 0;
		}
	}
}
